package com.apinji.interceptor;

import com.apinji.common.plugin.MD5Utils;
import com.apinji.common.plugin.Mutual;
import com.apinji.common.plugin.StrUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 拦截器：支付中心接口调用，进行签名验证
 */
@Aspect
@Component
public class SignInterceptor {

    public static final String PRIVATE_KEY = "Apin@123456";
//
//    @Around("((execution(* com.apinji..*Controller.*(..))) " +
//            "&& (!execution(* com.apinji..*Controller.callBack*(..)))) " +
//            "&& @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object signInterceptorBefore(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        String key = request.getHeader("key");
        if(StrUtils.isEmpty(key) || !StrUtils.checkUuid(key)) {
            return Mutual.invalidParamAppend("header key");
        }
        if(StrUtils.isEmpty(timestamp)) {
            return Mutual.invalidParamAppend("header timestamp");
        }

        long time = 0;
        try{
            time = Long.parseLong(timestamp);
        }catch (Exception e) {
            return Mutual.invalidParamAppend("header timestamp");
        }

        if(time == 0 || (time + 60*1000) < new Date().getTime()) {
            return Mutual.invalidParam("时间戳过期");
        }

        //
        String lastKey = key + PRIVATE_KEY + timestamp;
        String mySign = MD5Utils.MD5To32(lastKey);
        if(!mySign.equals(sign)) {
            return Mutual.invalidParamAppend("签名验证不通过");
        }
        //
        Object result = pjp.proceed();
        return result;
    }



}
